import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Checkbox,
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import Authorized from '../../utils/Authorized';
import defaultAvatar from '../../assets/admin_logo.png';
import styles from './UserList.less';
import {getAuthority} from '../../utils/authority';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['关闭', '运行中', '已上线', '异常'];

const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };
  return (
    <Modal
      title="新建规则"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="描述">
        {form.getFieldDecorator('desc', {
          rules: [{ required: true, message: 'Please input some description...' }],
        })(<Input placeholder="请输入" />)}
      </FormItem>
    </Modal>
  );
});

@connect(({ userList, loading }) => ({
  userList,
  loading: loading.models.userList,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    addInputValue: '',
    checkedGroupList: [],
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'userList/fetch',
    });
    dispatch({
      type : 'userList/fetchGroup',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      startIndex: (pagination.current - 1) * pagination.pageSize, //此处峻吉分页需要是第一项的序号，如第二页传10，而不是具体的分页码1，2，3
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'userList/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'userList/fetch',
      payload: {},
    });
  };

  toggleForm = () => {
    this.setState({
      expandForm: !this.state.expandForm,
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;

    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'userList/remove',
          payload: {
            no: selectedRows.map(row => row.no).join(','),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'userList/fetch',
        payload: values,
      });
    });
  };

  handleAddInput = (e) => {
    this.setState({
      addInputValue: e.target.value,
    });
  }

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleAdd = fields => {
    this.props.dispatch({
      type: 'userList/add',
      payload: {
        description: fields.desc,
      },
    });

    message.success('添加成功');
    this.setState({
      modalVisible: false,
    });
  };

  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    const { group } = this.props.userList;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="手机号码">
              {getFieldDecorator('phone')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="昵称">
              {getFieldDecorator('nickname')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="购买次数">
              {getFieldDecorator('buy_count')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="1">1+</Option>
                  <Option value="2">2+</Option>
                  <Option value="5">5+</Option>
                  <Option value="10">10+</Option>
                  <Option value="20">20+</Option>
                  <Option value="50">50+</Option>
                </Select>
              )}
            </FormItem>
          </Col>

        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="分组名称">
              {getFieldDecorator('groups')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="">请选择</Option>
                  {
                    group.forEach((v, i)=>{
                      return <Option value={v} key={`group_${i}`}>{ v }</Option>
                    })
                  }
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }
  onGroupChange = (checkedValues)=>{
    console.log(checkedValues);
    this.setState({
      checkedGroupList : checkedValues
    });
    //this.onGroupInfo.groupIds = checkedValues;
  }

  handleAddGroup = (e)=>{
    e.preventDefault();
    const {addInputValue} = this.state;
    const {dispatch}  = this.props;
    if(addInputValue == ''){
      return false;
    }
    dispatch({
      type : 'userList/addGroup',
      payload : {
        name : addInputValue
      },
    }).then(()=>{
      this.setState({
        addInputValue : ''
      });
    })
  };
  handleGroup = ()=>{
    //const {userIds} = this.onGroupInfo;
    const { selectedRows, checkedGroupList } = this.state;
    if(checkedGroupList.length == 0){
      //console.error('选中的分组用户为空');
      message.error('你还未选择分组');
      return;
    }
    //console.log(this.onGroupInfo);
    this.props.dispatch({
      type : 'userList/goodsGroup',
      payload: {
        ids : selectedRows.map(row => row.id).join(','),
        groups: checkedGroupList.join(',')
      }
    }).then(()=>{
      //message.success('分组成功');
      this.setState({
        modalVisible: false,
        checkedGroupList : [],
      });
    });

  };
  handleSelectGroup = row=>{
    console.log('row',[row]);
    let groups = [];  //计算出当前已有分组ID值
    this.props.userList.group.forEach(v=>{
      row.groups.forEach(s=>{
        if(v.name == s){
          groups.push(v.name);
        }
      })
    });

    this.setState({
      modalVisible: true,
      selectedRows : [row],
      checkedGroupList: groups,
    });
  };

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    console.log(this.props);
    const { userList: { data, group }, loading } = this.props;
    const { selectedRows, modalVisible, addInputValue, checkedGroupList } = this.state;

    const columns = [
      {
        title: '头像',
        dataIndex: 'headUrl',
        render:val=>{
          return <img src={val || defaultAvatar} width="30" height={30} />
        }
      },
      {
        title: '昵称',
        dataIndex: 'nickname',
      },
      {
        title: '手机号',
        dataIndex: 'phone',
      },
      {
        title: '购买次数',
        dataIndex: 'buy_count',
      },
      
    ];
    if(getAuthority() == 'business'){ //商家才可能对用户分组
      columns.push({
        title: '分组',
        dataIndex: 'groups',
      },
      {
        title: '操作',
        render: (text, record) => (
          <Authorized authority="business">
          <Fragment>
            <a href="javascript:;" onClick={()=>{this.handleSelectGroup(record)}}>分组</a>
          </Fragment>
          </Authorized>
        ),
      });
    }


    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
        <Menu.Item key="approval">批量审批</Menu.Item>
      </Menu>
    );

    return (
      <div>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            {
              getAuthority() == 'business' ? <div className={styles.tableListOperator}>
              {selectedRows.length > 0 && (
                <span>
                  <Button>分组</Button>
                </span>
              )}
            </div> : null
            }
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <Modal
          title="选择分组"
          visible={modalVisible}
          onOk={this.handleGroup}
          onCancel={() => this.handleModalVisible()}
        >
          <Form layout="inline" onSubmit={this.handleAddGroup}>
            <FormItem
              label="分组名"
            >
              <Input placeholder="输入新的分组名" onChange={this.handleAddInput} value={addInputValue} style={{width:300}} />
            </FormItem>
            <FormItem>
              <Button
                type="default"
                htmlType="submit"
              >
                新增
              </Button>
            </FormItem>
          </Form>
          <div style={{'marginTop':'24px'}}>
            <Checkbox.Group style={{ width: '100%' }} value={checkedGroupList} onChange={this.onGroupChange}>
              <Row >
                {
                  group.map(v=>{
                    return <Col span={8} key={v.id}><Checkbox value={v.name}>{v.name}</Checkbox></Col>
                  })
                }
              </Row>
            </Checkbox.Group>
          </div>
        </Modal>
      </div>
    );
  }
}
